package com.purchase.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import net.sf.json.JSONObject;
/**
 * 微信小程序二维码工具类
 * 
 */
public class QRCode_wxProgram {
	//微信小程序的appid AppSecret
	private static final String appid = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"sys.appid");
    private static final String AppSecret = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"sys.appSecret");
    private static final String uploadSysUrl = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"QRCode.logo");
    /**
     * @Title: GetUrl   
     * @Description: 获取小程序的  access_token
     * @author: JiangShuai
     * @param: @param imgName 待保存的图片名称
     * @param: @return
     * @param: @throws ClientProtocolException
     * @param: @throws IOException      
     * @return: String   图片的路径
     */
	public static String GetUrl(String page, String scene, String width, String imgName)
			throws ClientProtocolException, IOException {

		String uri = "";

		uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
				+ AppSecret;

		HttpGet httpGet = new HttpGet(uri);
		HttpClient httpClient = HttpClients.createDefault();
		HttpResponse res = httpClient.execute(httpGet);
		HttpEntity entity = res.getEntity();
		String result = EntityUtils.toString(entity, "UTF-8");
		JSONObject jsons = JSONObject.fromObject(result);
		String access_token = jsons.getString("access_token");
		try {
			return GetPostUrl(access_token, page, scene, width, imgName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 *  @Title: GetPostUrl   
	 * @Description: 获取二维码 信息图片
	 * @author: JiangShuai
	 * @param: @param access_token
	 * @param: @param page
	 * @param: @param scene
	 * @param: @param width
	 * @param: @param imgName
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String
	 */
    public static String GetPostUrl(String access_token,String page,String scene,String width,String imgName) throws Exception {
    	//接口B
        String url="http://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
        //接口C
        //String url ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("page", page);
         map.put("width", width);//图片大小
         map.put("scene", scene);
         //map.put("page", "pages/home/home");//你二维码中跳向的地址
         //map.put("page", "pages/product/product");
         //map.put("width", "230");//图片大小
         //scene 最多支持 20个 参数
         //map.put("scene", "B02S0002,B0000001,12");
         JSONObject json = JSONObject.fromObject(map);
         System.out.println(json);
        String  res= httpPostWithJSON(url
                     + access_token, json.toString(),imgName);
         System.out.println(res);
        return res;
    }

	//返回图片保存 ，根据 id 
	public static String httpPostWithJSON(String url, String json,String imgName)
                throws Exception {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
      
            StringEntity se = new StringEntity(json);
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                            "UTF-8"));
            httpPost.setEntity(se);
            // httpClient.execute(httpPost);
            HttpResponse response = httpclient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                        InputStream instreams = resEntity.getContent(); 
                        File saveFile = new File(uploadSysUrl+imgName+".png");
                           // 判断这个文件（saveFile）是否存在
                           if (!saveFile.getParentFile().exists()) {
                               // 如果不存在就创建这个文件夹
                               saveFile.getParentFile().mkdirs();
                           }
                   return saveToImgByInputStream(instreams, uploadSysUrl, imgName+".png");
                }
            }
            httpPost.abort();
            return null;
        } 
         
   /* @param instreams 二进制流
    * @param imgPath 图片的保存路径
    * @param imgName 图片的名称
    * @return
    *      1：保存正常
    *      0：保存失败
    */
   public static String saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
       if(instreams != null){
           try {
               File file=new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等
               FileOutputStream fos=new FileOutputStream(file);
                    
               byte[] b = new byte[1024];
               int nRead = 0;
               while ((nRead = instreams.read(b)) != -1) {
                   fos.write(b, 0, nRead);
               }
               fos.flush();
               fos.close();                
           } catch (Exception e) {
               return null;
               //e.printStackTrace();
           } finally {
               try {
                instreams.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
           }
       }
       return imgPath+imgName;
   }

	//然后是图片重合和增加字体
	@SuppressWarnings("static-access")
	public static void changeImage(String imageurl,String i ){
	        try { 
	//            InputStream imagein = new FileInputStream(
	//                    "D:/systemAvatarNew1.png");
	//            InputStream imagein2 = new FileInputStream(
	//                    "D:/qqfile/1852230493/FileRecv/4-02.png");
	        	
	        String as="D:\\erweima\\12.png";
	        	new QRCodeUtil().mkdirs(as);
            InputStream imagein = new FileInputStream(as);
            InputStream imagein2 = new FileInputStream(
                    imageurl);

            BufferedImage image = ImageIO.read(imagein);
            BufferedImage image2 = ImageIO.read(imagein2); 
            //image2.getWidth() - 160, image2.getHeight() - 155,
            Graphics g = image.getGraphics();
            g.drawImage(image2, 300, 230, 410,422,null);
//            g.drawImage(image2, image.getWidth() - image2.getWidth() - 195,
//                    image.getHeight() - image2.getHeight() - 190,
//                     340,349,null);
            OutputStream outImage = new FileOutputStream(
                    imageurl);
            JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(outImage);
            enc.encode(image);
            
            
            BufferedImage bimg=ImageIO.read(new FileInputStream(imageurl));  
            //得到Graphics2D 对象  
            Graphics2D g2d=(Graphics2D)bimg.getGraphics();  
            //设置颜色和画笔粗细  
            g2d.setColor(Color.black);  
            g2d.setStroke(new BasicStroke(5));  
            //String pathString = "D://qqfile/1852230493/FileRecv/SourceHanSansCN-/SourceHanSansCN-Heavy.otf";
//            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, new File(pathString));
            
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 36));  
            //g2d.setFont(Loadfont.loadFont(pathString, 45));  
            //绘制图案或文字  
            g2d.drawString("编号: "+i, 320, 700);  
          //  g2d.drawString(i, 450, 700);    
            
            ImageIO.write(bimg, "JPG",new FileOutputStream(imageurl));
            
            
            /*File fromFile = new File(imageurl);  
            File toFile = new File(imageurl);  
            Image Image1 =new Image();
            Image1.resizePng(fromFile, toFile, 1000, 1000, false);*/
            
               
            
            imagein.close();
            imagein2.close();
            outImage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

@SuppressWarnings("static-access")
public static void main(String[] args) {
	String page="pages/home/home";//你二维码中跳向的地址
	String scene="B02S0002,B0000001,12";
	String width="230";
	String imgName=new Utils().getUUID();
    //map.put("page", "pages/product/product");
    //map.put("width", "230");//图片大小
    //scene 最多支持 20个 参数
    //map.put("scene", "B02S0002,B0000001,12");
	try {
		String localFilePath=GetUrl(page, scene, width, imgName);
		String qiniuUrl=new QiniuUtil().getQiNiuUrl(localFilePath);
		System.out.println("qiniuUrl="+qiniuUrl);
		//changeImage("D:\\erweima\\13.png", "我认为贰234234");
	} catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}
